package com.codeos.khttp;

import com.codeos.khttp.request.KRequest;
import com.codeos.khttp.request.body.KHttpBody;
import com.codeos.khttp.response.KResponse;
import com.codeos.khttp.utils.KHttpUtils;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class KHttp {

    private Socket mSocket;
    private OutputStream mOutputStream;
    private OutputStreamWriter mWriter;
    private InputStream mInputStream;
    private InputStreamReader mReader;

    private KRequest mRequest;
    private KHttpListener mListener;

    public KHttp() {
        mSocket = new Socket();
    }

    private void initIO(String ip, int port) throws IOException {
        mSocket.connect(new InetSocketAddress(ip, port));
        mOutputStream = mSocket.getOutputStream();
        mWriter = new OutputStreamWriter(mOutputStream);
        mInputStream = mSocket.getInputStream();
        mReader = new InputStreamReader(mInputStream);
    }

    public KHttp addRequest(KRequest request) {

        mRequest = request;
        return this;
    }

    /**
     * 同步执行Http请求
     * @return
     */
    public KResponse start() {

        if(mRequest == null) {
            throw new IllegalArgumentException("please set KRequest first!");
        }
        try {
            initIO(mRequest.getRequestIP(), mRequest.getRequestPort());
            mRequest.request(mOutputStream, mWriter);

            mSocket.shutdownOutput();

            return new KResponse(readHttpResponse());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void run(final KHttpListener listener) {


        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    KResponse response = start();
                    if(listener != null) {
                        listener.onSuccess(response);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if(listener != null) {
                        listener.onError(-1, KHttpUtils.getStackTrace(e));
                    }
                }
            }
        }).start();
    }

    public StringBuffer readHttpResponse() throws IOException {
        BufferedReader br = new BufferedReader(mReader);
        StringBuffer sb = new StringBuffer();

        String strLine;
        while ((strLine = br.readLine()) != null) {
            sb.append(strLine);
        }

        return sb;
    }

//    private void sendBodyData() {
//        try {
//            mWriter.write(mHttpMethod + " " + mUrl.getTotalFilePath() + " " + mHttpProtocalVer +"\r\n");
//            mWriter.write("Host: "+mUrl.getHost()+":"+mUrl.getPort()+"\r\n");
//            mWriter.write("cache-control: no-cache\r\n");
//            mWriter.write("User-Agent: PostmanRuntime/7.6.1\r\n");
//
//            mWriter.write("Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*\r\n");
//            mWriter.write("Accept-Language: zh-cn\r\n");
//            mWriter.write("accept-encoding: gzip, deflate\r\n");
//            mWriter.write("content-type: multipart/form-data; boundary=--------------------------7daf10c20d06\r\n");
//            mWriter.write("content-length: 3749\r\n");
//            mWriter.write("Connection: keep-alive\r\n");
//            mWriter.write("\r\n");
//            mWriter.flush();
//            //-----------------------------------------------------------------
//            mWriter.write("----------------------------7daf10c20d06\r\n");                                                                  // 42
//            mWriter.flush();
//            mWriter.write("Content-Disposition: form-data; name=\"userfile\n\"; pictype=0&isurl=0&piclen=1485; filename=\"rr.jpg\"\r\n");   // 100
//            mWriter.write("Content-Type: image/jpeg\r\n\r\n");                                                                              // 28
//            mWriter.flush();
//
////                mWriter.write("Media type: audio/mpeg\r\n");
//            File picFile = new File("C:\\Users\\Administrator\\Desktop\\rr.jpg");
//            FileInputStream fis = new FileInputStream(picFile);
//            byte[] buf = new byte[1024];
//            int length = 0;
//            while((length = fis.read(buf)) != -1) {
//                mOutputStream.write(buf, 0, length);
//            }
////                mOutputStream.write("\r\n".getBytes());
//            mWriter.flush();
//
//            System.out.println("---------- after write file ----------");
//            mWriter.write("\r\n" +
//                    "----------------------------7daf10c20d06\r\n");
//            mWriter.flush();mWriterThread
//
//            //------------------------------
//
//            mWriter.write("Content-Disposition: form-data; name=\"userfile\n\"; pictype=1&isurl=0&piclen=1485; filename=\"tt.jpg\"\r\n");
//            mWriter.write("Content-Type: image/jpeg\r\n\r\n");
//            mWriter.flush();
//
////                mWriter.write("Media type: audio/mpeg\r\n");
//            File pic2File = new File("C:\\Users\\Administrator\\Desktop\\rr.jpg");
//            FileInputStream fis2 = new FileInputStream(pic2File);
//            byte[] buf2 = new byte[1024];
//            int length2 = 0;
//            while((length2 = fis2.read(buf2)) != -1) {
//                mOutputStream.write(buf2, 0, length2);
//            }
////                mOutputStream.write("\r\n".getBytes());
//            mWriter.flush();
//
//            System.out.println("---------- after write file2 ----------");
//            mWriter.write("\r\n" +
//                    "----------------------------7daf10c20d06\r\n");
//            mWriter.flush();
//
//            // json
//            mWriter.write("Content-Disposition: form-data; name=\"userfile\n\"; datatype=json&datalen=235\r\n");    // 77
//            mWriter.write("Content-Type: text/plain\r\n\r\n");  // 28
//            mWriter.flush();
//            // 228 235
//            mWriter.write("{\"sName\":\"张三\",\"sNation\":\"汉族\",\"sBirthDate\":\"2016-01-30\",\"sAddress\":\"南山区\",\"sIdNumber\":\"13301112345\",\"sStartDate\":\"2017-01-30 23:00:00\",\"sEndDate\":\"2017-02-30\",\"sCheckDate\":\"2017-01-30 23:00:00\",\"iResult\":0,\"bAlarm\":true,\"sRec\":\"\"}");
//            mWriter.write("\r\n" +
//                    "----------------------------7daf10c20d06--\r\n");
//            mWriter.flush();
//
////            printWriterContent();
////            mSocket.shutdownOutput();
//        } catch (Exception e) {
//            e.printStackTrace();
//            onError(-1, getStackTrace(e));
//        } finally {
//            // TODO release IO
//        }
//    }
}
